
const Service = require('egg').Service;

class MzdService extends Service {
  constructor() {
    super(...arguments);
    /**
     *@abstract 初始化连接的数据库 db1
    */
    this.client1 = this.app.mysql.get('db1');
    /**
     * @abstract 初始化表名
    */
    this.tableName = 'tx_signup';
  }

  /**
	* @param param 报名参数
	*/
  async send(param) {
    const { ctx } = this;
    const time = Date.now();

    const s1 = ctx.helper.sortASCII(param);
    const s2 = ctx.helper.md5([ param.apiid, param.key ].join(''));
    const sign = ctx.helper.md5([ s1, s2 ].join(''));
    const body = {
      ...param,
      time,
      sign,
    };
    try {
      const result = await this.ctx.curl('https://clueimport-cem.changan-mazda.com.cn/api/index/index', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        dataType: 'json',
        data: body,
      });
      const insertData = {
        ...param,
        content: JSON.stringify(result.data),
        createtime: new Date().getTime() / 1000,
      };
      const { createDb } = ctx.helper;
      const insertDb = await createDb(this.client1, this.tableName, insertData);
      if (insertDb.affectedRows === 1) {
        ctx.getLogger('bmLogger').info('bm success', insertData);
        return {
          code: 200,
          message: 'success',
          data: insertData,
        };
      }
      return {
        code: 500,
        message: '报名失败',
      };
    } catch (error) {
      throw new Error(`马自达报名失败${error}`);
    }
  }
}


module.exports = MzdService;
